package com.qilin.hscs.hm.mqtt.service.impl.entrance;

import com.qilin.hscs.hm.mqtt.service.common.ServiceCommon;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

/**
 * Created by 10188 on 2018/3/30.
 */
@Service
public class ServiceEntrance implements Observer<String> {

    private ServiceCommon service;

    @Autowired
    private ApplicationContext ctx;  //spting容器


    private static final Logger logger= LogManager.getLogger(ServiceEntrance.class.getName());
    @Override
    public void onSubscribe(Disposable disposable) {

    }

    @Override
    public void onNext(String s) {
        logger.info("【service入口类收到处理中心发送的消息】={}",s);
        String[] content = s.split("#");
        String hostName = content[0];
        String topicVar=content[1];
        String serviceName=null;
        if (topicVar.contains("rsp")){
            int i = topicVar.indexOf("/");
            int j = topicVar.lastIndexOf("/");
            String temp=topicVar.substring(i + 1, j);
            int x = temp.indexOf("/");
            serviceName = temp.substring(0, x);
        }else {
            int i = topicVar.indexOf("/");
            serviceName = topicVar.substring(i + 1, topicVar.length());
        }
        service = (ServiceCommon) ctx.getBean(serviceName);
        service.setTopicVar(topicVar);
        service.setMsg(content[2]);
        logger.debug(hostName + " " + service.getTopicVar() + " " + service.getMsg());
        service.initailData();
        service.handle();
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onComplete() {

    }
}
